//=============================================================================
#include "CTexture.h"

//=============================================================================
CTexture::CTexture() {
    TextureID = 0;
}

//=============================================================================
bool CTexture::OnLoad(char* File) {
    SDL_Surface* tempSurf = NULL;

    if((tempSurf = IMG_Load(File)) == NULL) {
        printf("Unable to load file : %s\n", File);
        return false;
    }

    OnLoad(tempSurf);

    SDL_FreeSurface(tempSurf);

    return true;
}

//-----------------------------------------------------------------------------
bool CTexture::OnLoad(SDL_Surface* Surface) {
    if(TextureID > 0) {
        glDeleteTextures(1, &TextureID);
        TextureID = 0;
    }

    glGenTextures(1, &TextureID);

    glBindTexture(GL_TEXTURE_2D, TextureID);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int Mode = GL_RGB;

    if(Surface->format->BytesPerPixel == 4) {
        Mode = GL_RGBA;
    }

    if(Surface->w != 512 && Surface->w != 64) {
        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Surface->w, Surface->h, Mode, GL_UNSIGNED_BYTE, Surface->pixels);
    }else{
        glTexImage2D(GL_TEXTURE_2D, 0, Mode, Surface->w, Surface->h, 0, Mode, GL_UNSIGNED_BYTE, Surface->pixels);
    }

    return true;
}

//=============================================================================
void CTexture::Bind() {
    glBindTexture(GL_TEXTURE_2D, TextureID);
}

//=============================================================================
void CTexture::RenderQuad(int X, int Y, int Width, int Height) {
    Bind();

    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f(X, Y, 0);
        glTexCoord2f(1, 0); glVertex3f(X + Width, Y, 0);
        glTexCoord2f(1, 1); glVertex3f(X + Width, Y + Height, 0);
        glTexCoord2f(0, 1); glVertex3f(X, Y + Height, 0);
    glEnd();
}

//=============================================================================
